package com.zxcl.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxcl.config.WhiteUrlsConfig;
import com.zxcl.constant.AuthConstant;
import com.zxcl.constant.BusinessEnum;
import com.zxcl.constant.HttpConstant;
import com.zxcl.model.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 描述: [全局token校验的过滤器]
 * 作者: zxcl
 */
@Component
@Log4j2
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;


    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 和前端约定好 token携带在header中 Authorization:Bearer xxxxx
     * 1.拿到请求路径
     * 2.判断放行
     * 3.拿token
     * 4.校验拦截
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("网关有请求进来，api为：{}",path);
        if (whiteUrlsConfig.getAllowUrls().contains(path)) {
            return chain.filter(exchange);
        }
        // 拿token
        String authorization = request.getHeaders().getFirst(AuthConstant.AUTHORIZATION);
        if (StringUtils.hasText(authorization)) {
            // 分隔
            String token = authorization.replaceFirst(AuthConstant.BEARER, "");
            if (StringUtils.hasText(token) && redisTemplate.hasKey(AuthConstant.LOGIN_TOKEN_PREFIX + token)) {
                return chain.filter(exchange);
            }
        }
        log.error("网关拦截请求,api为:{}", path);
        // 拦截
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(HttpConstant.CONTENT_TYPE, HttpConstant.APPLICATION_JSON);
        // 业务返回值 401（没有token）     请求200
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
